package com.huiminpay.message;

import com.alibaba.fastjson.JSON;
import com.huiminpay.model.Order;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/**
 * @ClassName ProducerSimple
 * @Author: longlong
 * @CreateDate: 2023/12/18 11:30
 */


@Slf4j
@Component
public class ProducerSimple2 {
    @Autowired
    RocketMQTemplate rocketMQTemplate;


    /**
     * 发送自定义格式消息
     *
     * @param topic
     * @param order
     */
    public void sendMsgByJson(String topic, Order order) {
        rocketMQTemplate.convertAndSend(topic, order);
        System.out.println("发送消息成功！");
    }

    /**
     * 同步发送延迟消息
     *
     * @param:
     * @return:
     */
    public void sendMsgByJsonDelay(String topic, Order order) {
        //将消息内容order转为json
        Message<Order> message = MessageBuilder.withPayload(order).build();
        //指定发送超时时间和延迟级别
        rocketMQTemplate.syncSend(topic, message, 1000, 3);
        log.info("发送消息成功：{}", order);
    }

    /**
     * 发送异步延迟消息
     */
    @SneakyThrows
    public void sendAsyncMsgByJsonDelay(String topic, Order order) {
        //将消息内容order转为json
        String jsonString = JSON.toJSONString(order);
        org.apache.rocketmq.common.message.Message message = new org.apache.rocketmq.common.message.Message(topic, jsonString.getBytes(Charset.forName("utf-8")));
        //设置延迟级别
        message.setDelayTimeLevel(3);
        rocketMQTemplate.getProducer().send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult.getSendStatus());
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });

        log.info("异步发送的消息是：{}", order);
    }


}
